import { defineStore } from 'pinia'
import { api } from '../api/client'
import { useMenuStore } from './menu'

interface UserInfo {
  id: string
  username: string
  full_name?: string
  email?: string
  enabled: boolean
}

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: null as UserInfo | null,
    loading: false,
  }),
  actions: {
    async login(username: string, password: string) {
      this.loading = true
      try {
        const resp = await api.post('/auth/login', { username, password })
        const token = resp.data?.access_token
        if (!token) throw new Error('登录失败')
        this.token = token
        localStorage.setItem('token', token)
        await this.fetchMe()
      } finally {
        this.loading = false
      }
    },
    async fetchMe() {
      const resp = await api.get('/auth/me')
      this.user = resp.data
    },
    logout() {
      this.token = ''
      this.user = null
      localStorage.removeItem('token')
      // 清空菜单树，避免保留旧权限
      try { useMenuStore().setTree([]) } catch {}
      location.href = '/home'
    },
  },
})